﻿@typeparam TItem where TItem : VrrpInstance

<MDialog @bind-Value="Value"
         MaxWidth="800"
         Persistent>
    <MCard>
        <MCardTitle>
            <span class="text-h5">VRRP 实例配置 - @Item.Name</span>
            <MSpacer />
            <MButton Icon
                     OnClick="CloseDialog">
                <MIcon>mdi-close</MIcon>
            </MButton>
        </MCardTitle>

        <MCardText>
            <MRow>
                <MCol Cols="12" Md="6">
                    <MSelect @bind-Value="Item.State"
                    ItemText="item=>item"
                    ItemValue="item=>item"
                             Items="_stateOptions"
                             Label="初始状态"
                             Outlined
                             Dense
                             Required
                             Rules="_requiredRules" />
                </MCol>
                <MCol Cols="12" Md="6">
                    <MSelect @bind-Value="Item.Interface"
                             ItemText="item=>item"
                             ItemValue="item=>item"
                             Items="_networkInterfaces"
                             Label="网络接口"
                             Outlined
                             Dense
                             Required
                             Rules="_requiredRules" />
                </MCol>
            </MRow>

            <MRow>
                <MCol Cols="12" Md="4">
                    <MTextField @bind-Value="Item.VirtualRouterId"
                                Label="虚拟路由器ID"
                                Type="number"
                                Outlined
                                Dense
                                Required
                                Rules="_vridRules" />
                </MCol>
                <MCol Cols="12" Md="4">
                    <MTextField @bind-Value="Item.Priority"
                                Label="优先级"
                                Type="number"
                                Outlined
                                Dense
                                Required
                                Rules="_priorityRules" />
                </MCol>
                <MCol Cols="12" Md="4">
                    <MTextField @bind-Value="Item.AdvertInt"
                                Label="通告间隔(秒)"
                                Type="number"
                                Outlined
                                Dense
                                Required
                                Rules="_intervalRules" />
                </MCol>
            </MRow>

            <MExpansionPanels Flat>
                <MExpansionPanel>
                    <MExpansionPanelHeader Color="primary" HideActions>
                        <span class="text-h6">认证配置</span>
                    </MExpansionPanelHeader>
                    <MExpansionPanelContent>
                        <MRow>
                            <MCol Cols="12" Md="6">
                                <MSelect @bind-Value="Item.Authentication.AuthType"
                                ItemValue="item=>item"
                                         ItemText="item=>item"
                                         Items="_authTypeOptions"
                                         Label="认证类型"
                                         Outlined
                                         Dense
                                         Required
                                         Rules="_requiredRules" />
                            </MCol>
                            <MCol Cols="12" Md="6">
                                <MTextField @bind-Value="Item.Authentication.AuthPass"
                                            Label="认证密码"
                                            Outlined
                                            Dense
                                            Required
                                            Rules="_authPassRules" />
                            </MCol>
                        </MRow>
                    </MExpansionPanelContent>
                </MExpansionPanel>

                <MExpansionPanel>
                    <MExpansionPanelHeader Color="primary" HideActions>
                        <span class="text-h6">虚拟IP地址</span>
                    </MExpansionPanelHeader>
                    <MExpansionPanelContent>
                        <MList>
                            @for (int i=0; i<Item.VirtualIpAddresses.Count;i++)
                            {
                                var vip = Item.VirtualIpAddresses[i];
                                <MListItem>
                                    <MListItemContent>
                                        <MTextField @bind-Value="vip.IpAddress"
                                        Label="虚拟IP (CIDR格式)"
                                        Outlined
                                        Dense
                                        Required
                                        Rules="_vipRules" />
                                    </MListItemContent>
                                    <MListItemAction>
                                        <MButton Icon
                                        Color="error"
                                        OnClick="@(() => RemoveVip(vip))">
                                            <MIcon>mdi-delete</MIcon>
                                        </MButton>
                                    </MListItemAction>
                                </MListItem>
                            }
                            <MListItem>
                                <MButton Color="primary"
                                Outlined
                                OnClick="AddVip">
                                    <MIcon Left>mdi-plus</MIcon>
                                    添加虚拟IP
                                </MButton>
                            </MListItem>
                        </MList>
                    </MExpansionPanelContent>
                </MExpansionPanel>

                <MExpansionPanel>
                    <MExpansionPanelHeader Color="primary" HideActions>
                        <span class="text-h6">高级配置</span>
                    </MExpansionPanelHeader>
                    <MExpansionPanelContent>
                        <MRow>
                            <MCol Cols="12" Md="6">
                                <MSwitch @bind-Value="Item.Nopreempt"
                                Label="不抢占模式"
                                MessagesGetter="context => context ? '已启用' : '已禁用'"
                                Dense />
                            </MCol>
                            <MCol Cols="12" Md="6">
                                <MTextField @bind-Value="Item.PreemptDelay"
                                Label="抢占延迟(秒)"
                                Type="number"
                                Outlined
                                Dense
                                Disabled="Item.Nopreempt" />
                            </MCol>
                        </MRow>

                        <MRow Class="mt-4">
                            <MCol Cols="12">
                                <MSelect @bind-Value="_selectedTrackScript"
                                Items="AvailableScripts"
                                Label="跟踪脚本"
                                Outlined
                                Dense
                                ItemText="script => script.Name"
                                ItemValue="script => script.Name">
                                    <ActivatorContent>
                                        <MListItemContent>
                                            <MListItemTitle>选择跟踪脚本</MListItemTitle>
                                        </MListItemContent>
                                    </ActivatorContent>
                                </MSelect>
                            </MCol>
                        </MRow>

                        <MRow>
                            <MCol Cols="12">
                                
                                <MChipGroup 
                                            Column
                                            Multiple>
                                    <MLabel>@_selectedTrackScript</MLabel>
                                    @for (int i = 0; i < Item.TrackScripts.Count; i++)
                                    {
                                        var script = Item.TrackScripts[i];
                                        <MChip Value="script.ScriptName"
                                               Close
                                               CloseIcon="mdi-delete"
                                               OnCloseClick="@((m) => RemoveTrackScript(script))">
                                            @script.ScriptName
                                        </MChip>
                                    }
                                </MChipGroup>
                            </MCol>
                        </MRow>
                    </MExpansionPanelContent>
                </MExpansionPanel>
            </MExpansionPanels>
        </MCardText>
        
        <MCardActions>
            <MSpacer />
            <MButton Color="primary"
                     OnClick="SaveItem">
                <MIcon Left>mdi-content-save</MIcon>
                保存
            </MButton>
            <MButton Color="secondary"
                     OnClick="CloseDialog">
                取消
            </MButton>
        </MCardActions>
    </MCard>
</MDialog>

@code {
    [Parameter]
    public bool Value { get; set; }

    [Parameter]
    public EventCallback<bool> ValueChanged { get; set; }

    [Parameter]
    public TItem Item { get; set; }

    [Parameter]
    public EventCallback<TItem> ItemChanged { get; set; }

    [Parameter]
    public EventCallback<TItem> OnSave { get; set; }

    [Parameter]
    public List<VrrpScript> AvailableScripts { get; set; } = new();

    private List<string> _stateOptions = new() { "MASTER", "BACKUP" };
    private List<string> _authTypeOptions = new() { "PASS", "AH" };
    private List<string> _networkInterfaces = new() { "eth0", "eth1", "bond0" };
    private string _selectedTrackScript;

    // 验证规则
    private List<Func<string, StringBoolean>> _requiredRules = new()
    {
        value => string.IsNullOrWhiteSpace(value) ? "必填字段" : true
    };

    private List<Func<int, StringBoolean>> _vridRules = new()
    {
        value => value < 0 || value > 255 ?
            "虚拟路由器ID必须是0-255之间的数字" : true
    };

    private List<Func<int, StringBoolean>> _priorityRules = new()
    {
        value => value < 1 || value > 254 ?
            "优先级必须是1-254之间的数字" : true
    };

    private List<Func<int, StringBoolean>> _intervalRules = new()
    {
        value =>  value <= 0 ?
            "通告间隔必须是正整数" : true
    };

    private List<Func<string, StringBoolean>> _authPassRules = new()
    {
        value => string.IsNullOrWhiteSpace(value) ? "认证密码不能为空" : true,
        value => value.Length > 8 ? "认证密码最多8个字符" : true
    };

    private List<Func<string, StringBoolean>> _vipRules = new()
    {
        value => string.IsNullOrWhiteSpace(value) ? "虚拟IP不能为空" : true,
        value => !System.Text.RegularExpressions.Regex.IsMatch(value, @"^\d+\.\d+\.\d+\.\d+\/\d+$") ? 
            "请输入有效的CIDR格式(如192.168.1.100/24)" : true
    };

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        
        // 确保至少有一个虚拟IP
        if (!Item.VirtualIpAddresses.Any())
        {
            Item.VirtualIpAddresses.Add(new VirtualIpAddress() { IpAddress = "192.168.1.100/24" });
        }
        
        // 确保有认证配置
        if (Item.Authentication == null)
        {
            Item.Authentication = new VrrpAuthentication();
        }
    }

    private void AddVip()
    {
        Item.VirtualIpAddresses.Add(new VirtualIpAddress() { IpAddress = "192.168.1.101/24" });
    }

    private void RemoveVip(VirtualIpAddress vip)
    {
        if (Item.VirtualIpAddresses.Count > 1)
        {
            Item.VirtualIpAddresses.Remove(vip);
        }
    }

    private void AddTrackScript()
    {
        if (!string.IsNullOrEmpty(_selectedTrackScript) &&
            !Item.TrackScripts.Any(s => s.ScriptName == _selectedTrackScript))
        {
            Item.TrackScripts.Add(new VrrpTrackScript
            {
                ScriptName = _selectedTrackScript,
                Weight = 0
            });
            _selectedTrackScript = null;
        }
    }

    private void RemoveTrackScript(VrrpTrackScript script)
    {
        Item.TrackScripts.Remove(script);
    }

    private async Task SaveItem()
    {
        // 确保至少有一个虚拟IP
        if (!Item.VirtualIpAddresses.Any())
        {
            Item.VirtualIpAddresses.Add(new VirtualIpAddress() { IpAddress = "192.168.1.100/24" });
        }

        await OnSave.InvokeAsync(Item);
        await CloseDialog();
    }

    private async Task CloseDialog()
    {
        Value = false;
        await ValueChanged.InvokeAsync(Value);
    }
}